package com.mwm.paiwei.meiye.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lianjiao.core.activity.BaseActivity;
import com.lianjiao.core.net.BaseListener;
import com.lianjiao.core.net.HttpUtil;
import com.lianjiao.core.net.RequestParams;
import com.lianjiao.core.utils.LogUtils;
import com.lianjiao.core.utils.LsToast;
import com.mwm.paiwei.meiye.AESUtils;
import com.mwm.paiwei.meiye.KeyBoardListener;
import com.mwm.paiwei.meiye.config.MeiYeConfig;
import com.mwm.paiwei.meiye.model.LoginBean;
import com.mwm.paiwei.meiye.util.ZipUtil;
import com.mwm.paiwei.meiye.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import roboguice.inject.InjectView;

/**
 * Created by wujamie on 17/3/1.
 */

public class WebViewActivity extends BaseActivity {
    static String TAG = "WebViewActivity";

    private WebViewActivity mySelf = this;
    @InjectView(R.id.wvWebview)
    private WebView wvWebview;
    /**
     * 更新完js重新启动APP
     */
    private String local_url = MeiYeConfig.local_url + "/index.html";
    private SharedPreferences prefense;
    private LoginBean loginBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);


        try {
            Bundle bundle = getIntent().getExtras();
            Log.e("ceshi", "file://" + local_url);

            local_url += "?token=" + bundle.getString("token");
            local_url += "&uid=" + bundle.getLong("uid");
            local_url += "&utype=" + bundle.getString("utype");
            Log.e("hello33",local_url+"...");
        } catch (Exception e) {
            e.printStackTrace();
        }

        prefense = getSharedPreferences("user", Context.MODE_PRIVATE);

        init();

        KeyBoardListener.getInstance(this).init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init() {
        WebSettings webSettings = wvWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(true);

        wvWebview.addJavascriptInterface(new getToken(), "meiye");

        wvWebview.setWebChromeClient(new WebChromeClient());
        wvWebview.setWebViewClient(new WebViewClient() {

            private WebResourceResponse editResponse() {
                try {
                    return new WebResourceResponse("application/x-javascript", "UTF-8", ZipUtil.UpZip(MeiYeConfig.FILE_PATH + "/index.zip", "index.js"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //需处理特殊情况
                return null;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                Log.e("kkk222", url);
                return true;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (Build.VERSION.SDK_INT < 21) {
                    if (url.contains("index.js")) {
                        Log.e("asdasdas111", url + "...");
                        return editResponse();
                    }
                }
                return super.shouldInterceptRequest(view, url);
            }

            //
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= 21) {
                    String url = request.getUrl().toString();
                    if (!TextUtils.isEmpty(url) && url.contains("index.js")) {
                        Log.e("asdasdas222", url + "...");
                        return editResponse();
                    }
                }
                return super.shouldInterceptRequest(view, request);
            }
        });
        //"content://com.android.htmlfileprovider/sdcard/index.html"
        wvWebview.loadUrl("file://" + local_url);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wvWebview != null) {
            wvWebview.destroy();
        }
    }

    public class getToken {
        @JavascriptInterface
        public void loginOut() {
            SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
            preferences.edit().clear().commit();
            Intent intent = new Intent(WebViewActivity.this,LoginActivity.class);
            intent.putExtra("isFromOut",true);
            startActivity(intent);
            WebViewActivity.this.finish();
        }

        @JavascriptInterface
        public void changeId(){
//            SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
//            preferences.edit().clear().commit();
            SharedPreferences.Editor editorNew = mContext.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
            editorNew.putLong("uid_new", -1);
            editorNew.putString("token_new", "");
            editorNew.putString("utype_new", "");
            editorNew.commit();

            Intent intent = new Intent(WebViewActivity.this,LoginActivity.class);
            intent.putExtra("isFromOut",true);
            startActivity(intent);
            WebViewActivity.this.finish();
        }

        @JavascriptInterface
        public void getLoginInfo() {
//            String url = MeiYeConfig.url + "Api/Auth/Token";
            String url = MeiYeConfig.url + "Api/Auth/TokenByMultiUser";
            RequestParams params = new RequestParams();
            params.put("userName", prefense.getString("username",""));// 注意：
            params.put("userPwd", AESUtils.decrypt(prefense.getString("username",""), prefense.getString("password","")));// 注意：
            HttpUtil.post(params, url, new BaseListener() {

                @Override
                public void onError(String err) {
                    closeProgressDialog();
                    SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                    preferences.edit().clear().commit();
                    startActivity(new Intent(WebViewActivity.this, LoginActivity.class));
                    WebViewActivity.this.finish();
                }

                @Override
                public void onComplete(String context) {
                    closeProgressDialog();
                    Log.e("hello555",context+"...");
                    try {
//                        json = new JSONObject(context);
//
//                        if (json.getString("result").equals("0")) {
//                            LsToast.show(mContext, json.getString("msg"));
//                            return;
//                        }
//                        long userId = json.getJSONObject("data").getLong("userId");
//                        String userToken = json.getJSONObject("data").getString("token");

                        loginBean = new Gson().fromJson(context, LoginBean.class);
                        if (loginBean.getResult() == 0) {
                            LsToast.show(mContext, loginBean.getMsg());
                            return;
                        }
                        SharedPreferences.Editor editorNew = mContext.getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                        if(loginBean.getData().getUserCount() == 1){
                            Log.e("maybe_11","one");
                            editorNew.putString("token_new",loginBean.getData().getUserTokens().get(0).getToken());
                            editorNew.commit();
                        }else {
                            List<LoginBean.DataBean.UserTokensBean> userTokens = loginBean.getData().getUserTokens();

                            Log.e("maybe_22","one");
                            for (int i = 0; i < userTokens.size(); i++) {
                                if(prefense.getString("utype_new", "").equals(userTokens.get(i).getUserType())){

                                    Log.e("maybe_33","one");
                                    editorNew.putString("token_new",loginBean.getData().getUserTokens().get(i).getToken());
                                    editorNew.commit();
                                }
                            }
                        }

//                        MeiYeConfig.user.setToken(userToken);
//                        SharedPreferences.Editor edit = prefense.edit();
//                        edit.putString("token_new",userToken);
//                        edit.commit();


                        Log.e("maybe_44",prefense.getString("token_new",prefense.getString("token_new","")+"...")
                        +prefense.getLong("uid_new",-1)+"..."+prefense.getString("utype_new", ""));

                        Map retMap = new HashMap<>();
                        retMap.put("token", prefense.getString("token_new",""));
                        retMap.put("uid", prefense.getLong("uid_new",-1));
                        retMap.put("utype", prefense.getString("utype_new", ""));
                        final String info = new JSONObject(retMap).toString();
                        Log.d(TAG, info);
                        mySelf.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                wvWebview.loadUrl("javascript:GetNewTokenAsync(" + info + ")");
                            }
                        });

                    } catch (Exception e) {
                        LsToast.show(mContext, "数据异常");
                    }
                }
            });
        }

        @JavascriptInterface
        public String getInfo() {
            return "获取手机内的信息！！";
        }

        @JavascriptInterface
        public void update() {
            String url = MeiYeConfig.url + "Api/Auth/GetAppVersions";
            RequestParams params = new RequestParams();

            HttpUtil.get(params, url, new BaseListener() {
                        @Override
                        public void onError(String err) {
                            LogUtils.e(TAG, err);
                            JSONObject json = null;
                            try {
                                json = new JSONObject(err);
                                LsToast.show(mContext, json.getString("msg"));
                            } catch (JSONException e) {
                                LsToast.show(mContext, "访问异常");
                            }
                        }

                        @Override
                        public void onComplete(String context) {
                            JSONObject json = null;
                            try {
                                json = new JSONObject(context);
                                if (json.getString("result").equals("1")) {
                                    String download_url = json.getJSONObject("data").getString("download_url");
                                    double version = json.getJSONObject("data").getDouble("versions");
                                    MeiYeConfig.JS_VERSION = (float) version;
                                    Intent intent = new Intent(WebViewActivity.this,LoadingActivity.class);
                                    intent.putExtra("isQzUpdate",true);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    LsToast.show(mContext, json.getString("msg"));
                                }
                            } catch (JSONException e) {
                                LsToast.show(mContext, "数据异常");
                            }
                        }
                    }
            );
        }

        @JavascriptInterface
        public void fetch(final int id, String url, String method, String headers, final String body) {
            if (url.startsWith("/")) {
                url = url.substring(1, url.length());
            }
            Map<String, String> map = new Gson().fromJson(headers, new TypeToken<HashMap<String, String>>() {
            }.getType());

            for (String s : map.keySet()) {
                if (TextUtils.isEmpty(map.get(s))) {
                    map.put(s, "");
                }
            }


            String result_url = MeiYeConfig.url + url;

            Map<String, String> map_body = null;
            if (TextUtils.isEmpty(body)) {
                map_body = new HashMap<>();
            } else {
                map_body = new Gson().fromJson(body, new TypeToken<HashMap<String, String>>() {
                }.getType());
                for (String s : map_body.keySet()) {
                    if (TextUtils.isEmpty(map_body.get(s))) {
                        map_body.put(s, "");
                    }
                }
            }

            if (method.equals("POST")) {

                OkHttpUtils
                        .post()
                        .url(result_url)
                        .headers(map)
                        .params(map_body)
                        .build()
                        .connTimeOut(20000)
                        .readTimeOut(20000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, final int dd) {
                                String str2 = "";
                                for (int i = 0; i < e.toString().length(); i++) {
                                    if (e.toString().charAt(i) >= 48 && e.toString().charAt(i) <= 57) {
                                        str2 += e.toString().charAt(i);
                                    }
                                }
                                final String finalStr = str2;

                                if (!TextUtils.isEmpty(finalStr)) {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.e("id", id + "..");
                                            wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + finalStr + "," + body + ")");
                                        }
                                    });
                                } else {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.e("id", id + "..");
                                            wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + 408 + "," + null + ")");
                                        }
                                    });
                                }

                            }

                            @Override
                            public void onResponse(final String response, int dd) {
                                mySelf.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + 200 + "," + response + ")");
                                    }
                                });
                            }
                        });

            } else {
                Log.e("sss", result_url);
                OkHttpUtils
                        .get()
                        .url(result_url)
                        .headers(map)
                        .params(map_body)
                        .build()
                        .connTimeOut(20000)
                        .readTimeOut(20000)
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int dd) {

                                String str2 = "";
                                for (int i = 0; i < e.toString().length(); i++) {
                                    if (e.toString().charAt(i) >= 48 && e.toString().charAt(i) <= 57) {
                                        str2 += e.toString().charAt(i);
                                    }
                                }
                                final String finalStr = str2;
                                if (!TextUtils.isEmpty(finalStr)) {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.e("id", id + "..");
                                            wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + finalStr + "," + body + ")");
                                        }
                                    });
                                } else {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.e("id", id + "..");
                                            wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + 408 + "," + null + ")");
                                        }
                                    });
                                }
                            }

                            @Override
                            public void onResponse(final String response, final int dd) {
                                mySelf.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wvWebview.loadUrl("javascript:fetchAsync (" + id + "," + 200 + "," + response + ")");
                                    }
                                });
                            }
                        });
            }
        }

        @JavascriptInterface
        public void hasNewVersion() {
            String url = MeiYeConfig.url + "Api/Auth/GetAppVersions";
            RequestParams params = new RequestParams();
            HttpUtil.get(params, url, new BaseListener() {
                        @Override
                        public void onError(String err) {
                            mySelf.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    wvWebview.loadUrl("javascript:hasNewVersionAsync(" + false + ")");
                                }
                            });
                        }

                        @Override
                        public void onComplete(String context) {

                            JSONObject json = null;
                            try {
                                json = new JSONObject(context);
                                final float version = (float) json.getJSONObject("data").getDouble("versions");
                                SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
                                final float js_version = sp.getFloat("js_version", -1);
                                Log.e("web",context+"..."+js_version+"..."+MeiYeConfig.JS_VERSION);
                                //TODO:>js_version 改爲 >MeiyeConfig.JS_VERSION
                                if (version > MeiYeConfig.JS_VERSION) {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            wvWebview.loadUrl("javascript:hasNewVersionAsync(" + version + ")");
                                        }
                                    });
                                } else {
                                    mySelf.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            wvWebview.loadUrl("javascript:hasNewVersionAsync(" + false + ")");
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                mySelf.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wvWebview.loadUrl("javascript:hasNewVersionAsync(" + false + ")");
                                    }
                                });
                            }
                        }
                    }
            );
        }
    }

    private void go2Login() {
        Intent intent = new Intent(mySelf, LoginActivity.class);
        intent.putExtra("isLoadNextActivity", true);
        startActivity(intent);
        mySelf.finish();
    }

    @Override
    public void onBackPressed() {
        if (wvWebview.canGoBack()) {
            wvWebview.goBack();
        } else {
            super.onBackPressed();
        }

    }

}
